package com.googlecode.utterlyidle.multipart;

import com.googlecode.utterlyidle.Entity;
import com.googlecode.utterlyidle.Rfc2616;

import java.io.UnsupportedEncodingException;

public class MultipartEntity {
    private Boundary closingLine;
    private Parts parts;

    public MultipartEntity(Boundary boundary, Parts parts) {
        this.closingLine = boundary.prefixed().suffixed();
        this.parts = parts;
    }

    public static MultipartEntity multipartEntity(Boundary boundary, Parts parts) {
        return new MultipartEntity(boundary, parts);
    }

    @Override
    public String toString() {
        return new StringBuilder().
                append(Rfc2616.HTTP_LINE_SEPARATOR).
                append(parts).
                append(Rfc2616.HTTP_LINE_SEPARATOR).
                append(closingLine).
                toString();
    }

    public byte[] toBytes() {
        try {
            byte[] separator = Rfc2616.HTTP_LINE_SEPARATOR.getBytes(Entity.DEFAULT_CHARACTER_SET);
            byte[] parts = this.parts.toBytes();
            return ByteArrays.combine(separator, parts, separator, closingLine.toBytes());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

}
